using Core;
using UnityEngine;

namespace g_gongjianta
{
    public class BulletCollisionComponent : UnitComponent<Bullet>, IAwake, IUpdate
    {
        private VisualComponent visual;
        private Transform checkPoint;
        private Vector2 checkSize;

        public override void Awake()
        {
            base.Awake();
            visual = Entity.Get<VisualComponent>();
            visual.AddLoadListener(OnVisualLoadHandler);
        }

        public override void Dispose()
        {
            if (IsDisposed) return;
            base.Dispose();
        }

        private void OnVisualLoadHandler()
        {
            visual.RemoveLoadListener(OnVisualLoadHandler);
            checkPoint = visual.transform.Find("Point");
            checkSize = checkPoint.localScale;
        }

        public void Update()
        {
            if (checkPoint == null) return;

            var center1 = (Vector2)checkPoint.position;
            var size1 = checkSize;

            var units = G.Unit().GetUnits<Monster>();

            foreach (var unit in units)
            {
                if (unit is not Monster monster || monster.Main.IsDead || monster.IsDisposed) continue;

                var center2 = (Vector2)monster.transform.position + monster.Conf.Offset;
                var size2 = monster.Conf.Size;

                var diff = center2 - center1;
                if (Mathf.Abs(diff.x) < (size1.x + size2.x) * 0.5f &&
                    Mathf.Abs(diff.y) < (size1.y + size2.y) * 0.5f)
                {
                    monster.Main.OnHurt();
                }
            }
        }
    }
}